import React, { useRef, useState, useEffect } from 'react';
import Video, { type VideoRef } from 'react-native-video';
import {
  View,
  Text,
  StyleSheet,
  ActivityIndicator,
  TouchableOpacity,
  Alert,
} from 'react-native';
import Orientation from 'react-native-orientation-locker';

interface CustomVideoPlayerProps {
  sourceUrl?: string;
  isLive?: boolean;
}

const CustomVideoPlayer = ({
  sourceUrl,
  isLive = false,
}: CustomVideoPlayerProps) => {
  const playerRef = useRef<VideoRef>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [paused, setPaused] = useState(false);

  // 默认使用您提供的测试链接
  const videoSource =
    sourceUrl ||
    'https://vd9.bdstatic.com/mda-rib1sdizi3y62h3i/mb/sc/cae_h264/1757680838873752981/mda-rib1sdizi3y62h3i.mp4?v_from_s=hkapp-haokan-nanjing&auth_key=1760351819-0-0-c66d55e66de0dc11462e69a773a0000c&bcevod_channel=searchbox_feed&pd=1&cr=2&cd=0&pt=3&logid=2219833983&vid=1361844505418127037&klogid=2219833983&abtest=';

  useEffect(() => {
    // 监听设备方向变化
    const listener = Orientation.addDeviceOrientationListener(orientation => {
      console.log('Device orientation changed:', orientation);
    });

    // 组件卸载时清理监听器
    return () => {
      Orientation.removeDeviceOrientationListener(listener);
      // 解锁方向
      Orientation.unlockAllOrientations();
    };
  }, []);

  const onLoad = () => {
    setLoading(false);
  };

  const onError = (e: any) => {
    setLoading(false);
    setError(true);
    console.log('Video Error:', e);
    Alert.alert(
      '播放错误',
      `无法播放视频: ${e.error?.localizedDescription || '未知错误'}`,
    );
  };

  const togglePlayPause = () => {
    setPaused(!paused);
  };

  const onEnterFullscreen = () => {
    // 进入全屏时锁定为横屏
    Orientation.lockToLandscape();
  };

  const onExitFullscreen = () => {
    // 退出全屏时解锁方向
    Orientation.unlockAllOrientations();
  };

  return (
    <View style={styles.container}>
      <Video
        ref={playerRef}
        style={styles.video}
        source={{
          uri: videoSource,
        }}
        onLoad={onLoad}
        onError={onError}
        paused={paused}
        controls={true}
        resizeMode="contain"
        onLoadStart={() => setLoading(true)}
        // 针对直播流的特殊配置

        // 直播不需要循环
        repeat={!isLive}
        // 全屏回调
        onFullscreenPlayerWillPresent={onEnterFullscreen}
        onFullscreenPlayerDidPresent={onEnterFullscreen}
        onFullscreenPlayerWillDismiss={onExitFullscreen}
        onFullscreenPlayerDidDismiss={onExitFullscreen}
        // 启用全屏按钮
        // fullscreen={true}
      />

      {loading && (
        <View style={styles.overlay}>
          <ActivityIndicator size="large" color="#fff" />
          <Text style={styles.loadingText}>
            {isLive ? '正在加载直播...' : '正在加载视频...'}
          </Text>
        </View>
      )}

      {error && (
        <View style={styles.overlay}>
          <Text style={styles.errorText}>视频播放失败</Text>
          <TouchableOpacity
            style={styles.retryButton}
            onPress={() => {
              setError(false);
              setLoading(true);
              // 重试
              playerRef.current?.seek(0);
            }}
          >
            <Text style={styles.retryText}>重试</Text>
          </TouchableOpacity>
        </View>
      )}

      <TouchableOpacity
        style={styles.playPauseButton}
        onPress={togglePlayPause}
      >
        <Text style={styles.playPauseText}>{paused ? '播放' : '暂停'}</Text>
      </TouchableOpacity>

      {isLive && (
        <View style={styles.liveIndicator}>
          <View style={styles.liveDot} />
          <Text style={styles.liveText}>LIVE</Text>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000',
  },
  video: {
    flex: 1,
  },
  overlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0,0,0,0.7)',
  },
  loadingText: {
    color: '#fff',
    marginTop: 10,
    fontSize: 16,
  },
  errorText: {
    color: '#ff4444',
    fontSize: 16,
    marginBottom: 20,
  },
  retryButton: {
    backgroundColor: '#6A4CE6',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  retryText: {
    color: '#fff',
    fontSize: 14,
  },
  playPauseButton: {
    position: 'absolute',
    bottom: 20,
    alignSelf: 'center',
    backgroundColor: 'rgba(0,0,0,0.5)',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  playPauseText: {
    color: '#fff',
    fontSize: 14,
  },
  liveIndicator: {
    position: 'absolute',
    top: 20,
    left: 20,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 0, 0, 0.8)',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 4,
  },
  liveDot: {
    width: 8,
    height: 8,
    backgroundColor: '#fff',
    borderRadius: 4,
    marginRight: 5,
  },
  liveText: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: 12,
  },
});

export default CustomVideoPlayer;
